﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;

using PortalFileUrls = Kiiro.Common.Utility.Constants.PortalFileUrls;
using ProjectFileUrls = Kiiro.Common.Utility.Constants.ProjectFileUrls;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.HtmlControls;
using System.Web.UI;

namespace Kiiro.SiteDefinition.ProjectPages
{
    public partial class AllDiscussion : BasePage
    {
        public Pager V2Pager
        {
            get { return ( Pager ) v2Pager; }
        }

        public WelcomeMessagePanel V2WelcomeMessagePanel
        {
            get { return ( WelcomeMessagePanel ) v2WelcomeMessagePanel; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        private List<User> discussionUsers;
        public List<User> DiscussionUsers
        {
            get { return discussionUsers; }
            set { discussionUsers = value; }
        }

        private List<Discussion> discussions = new List<Discussion> ( );
        private List<Discussion> Discussions
        {
            get { return discussions; }
            set { discussions = value; }
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            AddCommandButtons ( );

            litTitle.Text = "All Discussions";
            if ( KiiroMaster.V2Header.Project != null && !string.IsNullOrEmpty ( KiiroMaster.V2Header.Project.Title ) )
            {
                litTitle.Text = KiiroMaster.V2Header.Project.Title + " - All Discussions";
            }

            V2Pager.NextClick += new EventHandler ( RePopulatePage );
            V2Pager.PrevClick += new EventHandler ( RePopulatePage );
            V2Pager.EntitiesPerPageChange += new EventHandler ( RePopulatePage );

            discussions = DiscussionModel.GetDiscussionsByIds ( new List<int> ( ), SiteCollectionId, ServerRelativeUrl );

            if ( !IsPostBack )
            {
                V2Pager.SortExpression = "LastReply";
                PopulatePage ( );
            }
        }

        #region Page Related Methods

        private void PopulatePage ( )
        {
            if ( Discussions != null && Discussions.Count > 0 )
            {
                List<int> userIds = new List<int> ( );
                foreach ( Discussion discussion in Discussions )
                {
                    userIds.Add ( discussion.CreatedBy.Id );
                    userIds.Add ( discussion.ModifiedBy.Id );
                    if ( discussion.Comments.Count > 0 )
                    {
                        if ( discussion.Comments [ 0 ] != null )
                        {
                            userIds.Add ( discussion.Comments [ 0 ].CreatedBy.Id );
                            userIds.Add ( discussion.Comments [ 0 ].ModifiedBy.Id );
                        }
                    }
                }

                if ( userIds != null && userIds.Count > 0 )
                    DiscussionUsers = UserModel.GetUsersByIds ( userIds, SiteCollectionId, ServerRelativeUrl );

                SortList ( );

                V2Pager.PopulatePager ( Discussions.Count, Constants.PagerEntity.Discussions );

                rptDiscussions.DataSource = discussions.GetRange ( V2Pager.PagingIndex, V2Pager.DisplayedCount );
                rptDiscussions.DataBind ( );

                if ( rptDiscussions.Items.Count > 0 )
                {
                    HtmlTableRow trDiscussion = ( HtmlTableRow ) rptDiscussions.Items [ rptDiscussions.Items.Count - 1 ].FindControl ( "trDiscussion" );
                    trDiscussion.Attributes.Add ( "class", "borderless" );
                }
            }
            else
            {
                pnlPanel.Visible = false;
                v2Pager.Visible = false;
                v2WelcomeMessagePanel.Visible = true;
                V2WelcomeMessagePanel.ShowPanel = true;
                V2WelcomeMessagePanel.ServerRelativeUrl = ServerRelativeUrl;
                V2WelcomeMessagePanel.ShowHidePanel ( Constants.PagerEntity.Discussions, PermissionBitsDiscussions );

            }
        }

        private void AddCommandButtons ( )
        {
            if ( PermissionBitsDiscussions [ 0 ] )
            {
                LinkButton btnCreate = new LinkButton ( );
                btnCreate.Text = "Create a new Discussion";
                btnCreate.Attributes.Add ( "class", "icon-add" );
                btnCreate.Click += new EventHandler ( btnCreate_Click );
                NavigationSub.Commands.Add ( btnCreate );
            }
        }

        protected void btnCreate_Click ( object sender, EventArgs e )
        {
            Response.Redirect ( ServerRelativeUrl + ProjectFileUrls.DiscussionNew );
        }

        protected void rptDiscussions_ItemDataBound ( object sender, RepeaterItemEventArgs e )
        {
            if ( e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem )
            {
                Discussion discussion = ( Discussion ) e.Item.DataItem;

                HyperLink lnkDiscussion = ( HyperLink ) e.Item.FindControl ( "lnkDiscussion" );
                if ( lnkDiscussion != null )
                {
                    if ( discussion.Title.Length >= 42 )
                    {
                        lnkDiscussion.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( discussion.Title.Substring ( 0, 42 ) ) + "...";
                    }
                    else
                    {
                        lnkDiscussion.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( discussion.Title );
                    }
                    lnkDiscussion.NavigateUrl = String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, ProjectFileUrls.DiscussionDisplay, discussion.Id );
                }

                Image imgAttachment = ( Image ) e.Item.FindControl ( "imgAttachment" );
                if ( imgAttachment != null)
                {
                    int attachmewntsCount = discussion.AttachmentList.Count;
                    if (discussion.Comments.Count > 0)
                    {
                        foreach (Comment comment in discussion.Comments)
                        {
                            attachmewntsCount += comment.AttachmentList.Count;
                        }
                    }
                    if (attachmewntsCount > 0)
                    {
                        imgAttachment.Visible = true;
                        imgAttachment.AlternateText = string.Format("This discussion has {0} attachment{1}",
                            attachmewntsCount, discussion.AttachmentList.Count > 1 ? "s" : "");
                    }
                }

                Literal litText = ( Literal ) e.Item.FindControl ( "litText" );
                if ( litText != null )
                {
                    if ( !string.IsNullOrEmpty ( discussion.HTMLText ) )
                        litText.Text = discussion.HTMLText;
                    else
                        litText.Text = SPHelpers.CheckTextForLinks ( discussion.Text.Replace ( "\r\n", " <br/>" ) );
                }

                Label lblComments = ( Label ) e.Item.FindControl ( "lblComments" );
                if ( lblComments != null )
                {
                    lblComments.Text = discussion.NumberOfComments > 0 ? discussion.NumberOfComments.ToString ( ) : "0";
                }

                //Get Created By User By ID
                if ( discussion.CreatedBy != null )
                {
                    User createdBy = DiscussionUsers.Find ( x => x.Id == discussion.CreatedBy.Id );
                    if ( createdBy != null )
                    {
                        HyperLink lnkStartedBy = ( HyperLink ) e.Item.FindControl ( "lnkStartedBy" );
                        if ( lnkStartedBy != null )
                        {
                            lnkStartedBy.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( createdBy.FullName );
                            if ( !createdBy.IsDeleted )
                                lnkStartedBy.NavigateUrl = String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, PortalFileUrls.UserDisplay, createdBy.SPUserId );
                        }

                        Image imgStartedBy = ( Image ) e.Item.FindControl ( "imgStartedBy" );
                        if ( imgStartedBy != null )
                        {
                            imgStartedBy.ImageUrl = createdBy.PictureUrl ?? "/_layouts/images/Kiiro/person-thumb.gif";
                        }
                    }

                    Label lblStartedByDate = ( Label ) e.Item.FindControl ( "lblStartedByDate" );
                    if ( lblStartedByDate != null )
                    {
                        if ( discussion.ModifiedDate != null && discussion.ModifiedDate != DateTime.MinValue )
                            lblStartedByDate.Text = FormattingHelpers.DateTimeToTimeAgoString ( discussion.ModifiedDate );
                        else
                            lblStartedByDate.Text = FormattingHelpers.DateTimeToTimeAgoString ( discussion.CreatedDate );
                    }
                }

                //Get Last Reply By User By ID
                if ( discussion.Comments != null && discussion.Comments.Count > 0 && discussion.Comments [ discussion.Comments.Count -1  ].ModifiedBy != null )
                {
                    User lastReplyBy = DiscussionUsers.Find(x => x.Id == discussion.Comments[discussion.Comments.Count - 1].ModifiedBy.Id);
                    if ( lastReplyBy != null )
                    {
                        HyperLink lnkLastReplyBy = ( HyperLink ) e.Item.FindControl ( "lnkLastReplyBy" );
                        if ( lnkLastReplyBy != null )
                        {
                            lnkLastReplyBy.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( lastReplyBy.FullName );
                            if ( !lastReplyBy.IsDeleted )
                                lnkLastReplyBy.NavigateUrl = String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, PortalFileUrls.UserDisplay, lastReplyBy.SPUserId );
                        }
                    }

                    Label lblLastReplyDate = ( Label ) e.Item.FindControl ( "lblLastReplyDate" );
                    if ( lblLastReplyDate != null )
                    {
                        if (discussion.Comments != null && discussion.Comments[discussion.Comments.Count - 1].ModifiedDate != DateTime.MinValue)
                            lblLastReplyDate.Text = FormattingHelpers.DateTimeToTimeAgoString(discussion.Comments[discussion.Comments.Count - 1].ModifiedDate);
                        else
                            lblLastReplyDate.Text = FormattingHelpers.DateTimeToTimeAgoString(discussion.Comments[discussion.Comments.Count - 1].CreatedDate);
                    }
                }
            }
        }

        public static int CompareByLastCommentDateAsc ( Discussion x, Discussion y )
        {
            if ( x.Comments.Count == 0 )
            {
                if ( y.Comments.Count == 0 )
                    return 0;
                else
                    return -1;
            }
            else
            {
                if ( y.Comments.Count == 0 )
                    return 1;
                else
                {
                    int retval = y.Comments [ 0 ].ModifiedDate.CompareTo ( x.Comments [ 0 ].ModifiedDate );

                    if ( retval != 0 )
                        return retval;
                    else
                        return y.LastCommentDate.CompareTo ( x.LastCommentDate );
                }
            }
        }

        #endregion

        #region Pager Related Methods

        private void SortList ( )
        {
            replySort.Visible = false;
            commentsSort.Visible = false;
            startedSort.Visible = false;

            Literal sortText = replySort;
            string sortTextTemplate = "<img src='/_layouts/images/Kiiro/icon-sort-{0}.gif' />";

            switch ( V2Pager.SortExpression )
            {
                case "NumberOfComments":
                    sortText = commentsSort;
                    discussions.Sort ( delegate ( Discussion d1, Discussion d2 ) { return d1.NumberOfComments.CompareTo ( d2.NumberOfComments ); } );
                    break;
                case "StartedBy":
                    sortText = startedSort;
                    discussions.Sort ( delegate ( Discussion d1, Discussion d2 ) { return d1.CreatedDate.CompareTo ( d2.CreatedDate ); } );
                    break;
                case "LastReply":
                default:
                    sortText = replySort;
                    //removed this line to make the default sort consistent with Recent Discussions
                    //discussions.Sort ( CompareByLastCommentDateAsc );
                    break;
            }

            sortText.Visible = true;

            if ( V2Pager.SortDirection == SortDirection.Ascending )
            {
                sortText.Text = string.Format ( sortTextTemplate, "asc" );
            }
            else
            {
                sortText.Text = string.Format ( sortTextTemplate, "desc" );
                discussions.Reverse ( );
            }
        }

        private void RePopulatePage ( object sender, EventArgs e )
        {
            PopulatePage ( );
        }

        protected void SortBy_Click ( object sender, EventArgs e )
        {
            LinkButton link = ( LinkButton ) sender;
            if ( V2Pager.SortDirection == SortDirection.Ascending && V2Pager.SortExpression == link.CommandArgument )
                V2Pager.SortDirection = SortDirection.Descending;
            else
                V2Pager.SortDirection = SortDirection.Ascending;
            V2Pager.SortExpression = link.CommandArgument;

            V2Pager.IsSortClick = true;
            V2Pager.DisplayedCount = rptDiscussions.Items.Count;
            PopulatePage ( );
        }

        #endregion
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.ProjectPages/Discussions/AllDiscussion.aspx.cs $
 * 
 * 31    2/08/10 2:28p Camerons
 * 
 * 30    1/15/10 12:36p Camerons
 * 
 * 29    1/15/10 9:49a Camerons
 * 
 * 28    1/15/10 9:14a Camerons
 * 
 * 27    1/13/10 7:25p Camerons
 * 
 * 26    1/06/10 12:39p Camerons
 * 
 * 25    12/08/09 10:38a Shafia
 * 
 * 24    26/11/09 3:35p Shafia
 * 
 * 23    26/11/09 2:23p Shafia
 * 
 * 22    26/11/09 12:27p Shafia
 * discussions now show discussion text
 * 
 * 21    29/10/09 3:17p Camerons
 * 
 * 20    28/10/09 11:01a Camerons
 * 
 * 19    26/10/09 2:54p Shafia
 * 
 * 18    10/26/09 9:36a Adamw
 * 
 * 17    10/23/09 5:23p Adamw
 * Case 348
 * 
 * 16    23/10/09 2:41p Shafia
 * 
 * 15    16/10/09 2:18p Shafia
 * trim discussion link to 45 character and then show '...'
 * 
 * 14    16/10/09 10:32a Shafia
 * 
 * 13    16/10/09 9:56a Shafia
 * 
 * 12    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 11    25/09/09 10:44a Shafia
 * fixed sort method to retain page index and display correct number of
 * rows when sort is clicked.
 * 
 * 10    23/09/09 4:34p Shafia
 * implemented the new WelcomeMessagePanel user control on Projects,
 * Users, CustomLists, Work, Documents, and Discussions pages.
 * Links are being displayed based on PermissionsBits[Entity]
 * 
 * 9     22/09/09 9:46a Shafia
 * 
 * 8     21/09/09 12:42p Shafia
 * 
 * 7     18/09/09 2:33p Shafia
 * New Pager Implemented. All data binding is done on the page itself not
 * on the Pager control
 * 
 * 6     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/